#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
Kimi调试脚本
用于调试Kimi页面元素定位问题
"""

import asyncio
import os
import sys
from playwright.async_api import async_playwright

# 添加项目根目录到Python路径
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

async def debug_kimi_page():
    """调试Kimi页面元素"""
    print("开始调试Kimi页面...")
    
    async with async_playwright() as p:
        try:
            # 连接到Camoufox浏览器
            ws_endpoint = os.environ.get('CAMOUFOX_WS_ENDPOINT')
            if not ws_endpoint:
                print("错误: 未设置 CAMOUFOX_WS_ENDPOINT 环境变量")
                return False
                
            print(f"连接到浏览器: {ws_endpoint}")
            browser = await p.firefox.connect(ws_endpoint, timeout=30000)
            print(f"浏览器连接成功: {browser.version}")
            
            # 创建新页面并导航到Kimi
            print("创建新页面并导航到Kimi...")
            page = await browser.new_page()
            await page.goto("https://www.kimi.com/chat", wait_until="domcontentloaded", timeout=90000)
            print(f"页面加载完成: {page.url}")
            
            # 等待页面加载
            await asyncio.sleep(5)
            
            # 保存页面截图和HTML
            print("保存页面截图和HTML...")
            os.makedirs("errors_py", exist_ok=True)
            await page.screenshot(path="errors_py/kimi_debug.png", full_page=True)
            
            html_content = await page.content()
            with open("errors_py/kimi_debug.html", "w", encoding="utf-8") as f:
                f.write(html_content)
            print("页面信息已保存到 errors_py 目录")
            
            # 尝试不同的选择器
            selectors_to_try = [
                'textarea[placeholder*="请输入"]',
                'textarea',
                '[contenteditable="true"]',
                '.chat-input textarea',
                '#chat-input',
                '[data-testid="chat-input"]',
                'div[contenteditable="true"]',
                'input',
                '[role="textbox"]',
                '.textarea',
                '.input',
            ]
            
            print("\n尝试不同的选择器:")
            for selector in selectors_to_try:
                try:
                    locator = page.locator(selector)
                    count = await locator.count()
                    print(f"  {selector}: 找到 {count} 个元素")
                    
                    if count > 0:
                        for i in range(min(count, 3)):  # 最多检查前3个元素
                            try:
                                element = locator.nth(i)
                                is_visible = await element.is_visible()
                                is_enabled = await element.is_enabled()
                                bounding_box = await element.bounding_box()
                                tag_name = await element.evaluate("el => el.tagName")
                                
                                print(f"    元素 {i}: tag={tag_name}, visible={is_visible}, enabled={is_enabled}, box={bounding_box}")
                                
                                # 如果是可见的textarea或input，尝试获取placeholder
                                if is_visible and tag_name.lower() in ['textarea', 'input']:
                                    try:
                                        placeholder = await element.get_attribute("placeholder")
                                        print(f"      placeholder: {placeholder}")
                                    except:
                                        pass
                                        
                                # 如果是contenteditable的div，获取文本内容
                                if is_visible and tag_name.lower() == 'div':
                                    try:
                                        has_contenteditable = await element.get_attribute("contenteditable")
                                        if has_contenteditable:
                                            text_content = await element.text_content()
                                            print(f"      contenteditable, text_content: {text_content[:50] if text_content else 'None'}")
                                    except:
                                        pass
                            except Exception as e:
                                print(f"    检查元素 {i} 时出错: {e}")
                except Exception as e:
                    print(f"  {selector}: 出错 {e}")
            
            # 尝试查找按钮元素
            print("\n查找按钮元素:")
            button_selectors = [
                'button[aria-label="发送"]',
                'button[type="submit"]',
                '.send-button',
                '.submit-button',
                'button:has-text("发送")',
                'button:has-text("Submit")',
                '[data-testid="send-button"]',
                'button',
            ]
            
            for selector in button_selectors:
                try:
                    locator = page.locator(selector)
                    count = await locator.count()
                    print(f"  {selector}: 找到 {count} 个元素")
                    
                    if count > 0:
                        for i in range(min(count, 3)):  # 最多检查前3个元素
                            try:
                                element = locator.nth(i)
                                is_visible = await element.is_visible()
                                is_enabled = await element.is_enabled()
                                bounding_box = await element.bounding_box()
                                text_content = await element.text_content()
                                
                                print(f"    按钮 {i}: text={text_content[:30] if text_content else 'None'}, visible={is_visible}, enabled={is_enabled}, box={bounding_box}")
                            except Exception as e:
                                print(f"    检查按钮 {i} 时出错: {e}")
                except Exception as e:
                    print(f"  {selector}: 出错 {e}")
            
            print("\n调试完成，请查看 errors_py 目录中的文件来分析页面结构")
            return True
            
        except Exception as e:
            print(f"调试过程中发生错误: {e}")
            import traceback
            traceback.print_exc()
            return False
        finally:
            try:
                await browser.close()
                print("浏览器连接已关闭")
            except:
                pass

if __name__ == "__main__":
    # 设置环境变量用于测试
    os.environ['CAMOUFOX_WS_ENDPOINT'] = 'ws://127.0.0.1:9222'
    
    # 运行调试
    success = asyncio.run(debug_kimi_page())
    if success:
        print("✅ Kimi调试完成")
        sys.exit(0)
    else:
        print("❌ Kimi调试失败")
        sys.exit(1)